import { Module } from 'vuex'
import { ILoginState, ILoginType, ISysUser } from './type'
import { IRootState } from '../type'
import { accountLoginRequest, getUserMenu } from '@/service/login'
import { ILoginAccount } from '@/service/login/type'
import { localCache } from '@/utils/cache'
import router from '@/router'
import { type, msg, ResponseCode, dataProcessing } from '@/global'
import { getUserRoutes } from '@/utils/map-menus'

// Module 的两个类型是必填项，没有默认值，所以必须准备好
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenu: [],
      menuFlatMap: []
    }
  },
  mutations: {
    changeUserInfo(state, loginResData: ILoginType) {
      const userInfo = loginResData.sysUser
      state.userInfo = userInfo
      localCache.setCache('userInfo', userInfo)
    },
    changeUserMenu(state, menu: any) {
      state.userMenu = menu
      localCache.setCache('userMenu', menu)

      // 构建动态路由
      const userRoutes = getUserRoutes(menu)
      userRoutes?.forEach((item) => {
        router.addRoute('main', item)
      })
    },
    changePrintUserMenu(state) {
      console.log('login模块打印路由：', router)
    }
  },
  actions: {
    async loginAction({ commit }, payload: ILoginAccount) {
      const loginRes: type.ResponseType = await accountLoginRequest(payload)
      if (!dataProcessing.isResSuccess(loginRes)) return

      commit('changeUserInfo', loginRes.data)

      const menuRes: type.ResponseType = await getUserMenu()
      if (!dataProcessing.isResSuccess(menuRes)) return
      commit('changeUserMenu', menuRes.data)

      router.push('/main/system/overview')
    },

    printUserMenuAction({ commit }) {
      commit('changePrintUserMenu')
    },

    loadLocalAction({ commit }) {
      const menus = localCache.getCache('userMenu')
      commit('changeUserMenu', menus)
    }
  }
}

export { loginModule }
